local skynet = require "skynet"
local redis_tool = require "redis_tool"
local cjson = require "cjson"

local datashare = {}

local function gen_token_by_userid(account, userid, channel, login_acc_type)
    local info = {
        userid = userid,
        account = account,
        channel = channel,
        login_acc_type = login_acc_type
    }
    local res = cjson.encode(info)
    return res
end

--login_acc_type 1 为手机 2 为账号
function datashare.save_user_login(account, userid, channel, login_acc_type)
    log.info('save_user_login:', account, userid, channel, login_acc_type)
    --也要记录channel
    local token = gen_token_by_userid(account, userid, channel, login_acc_type)  
    local key = 'playerinfo:'..userid
    redis_tool.safe_hset(key, 'userid', userid, 'token', token, 'account', account)
    return token
end


local GuestIdBase = 800000000
--给机器人生成id号
function datashare.get_guset_id(account, channel)
    local token, first_login
    --通过设备id和channel来索引userid
    local user_id = redis_tool.safe_hget( 'acc:'..account..':'..channel, 'userid' )  
    if not user_id then
        local guest_index = redis_tool.safe_incr('guest_index')
        log.info("get_guset_id guest_index=", guest_index)
        user_id = tonumber(guest_index) + GuestIdBase
        redis_tool.safe_hset( 'acc:'..account..':'..channel, 'userid', user_id )

        token = gen_token_by_userid(account, user_id, channel)
        redis_tool.safe_hset('playerinfo:'..user_id, 'userid', user_id, 'token', token, 'channel', channel)
        first_login = true
    else
        token = redis_tool.safe_hget( 'playerinfo:'..user_id, 'token' )
        log.info("datashare.get_guset_id token=", token)
    end
    
    local recharge_id = redis_tool.safe_hget( 'playerinfo:'..user_id, 'guest_recharge_id' )
    if recharge_id then recharge_id = tonumber(recharge_id) end
    return {user_id = tonumber(user_id), token = token, first_login = first_login, recharge_id = recharge_id}
end


return datashare
